<?php

namespace App\Models;

use Carbon\Carbon;

class Order extends BaseModel
{
    protected $table = 'tiku_order';
    public const CREATED_AT = null;
    public const UPDATED_AT = null;

    protected $fillable = [
        'userId',
        'courseId',
        'tradeNo',
        'price',
        'type',
        'buyAt',
        'wxNonceStr',
        'wxSign',
        'wxPrepayId',
        'relationId'
    ];

    protected $appends = ['statusText', 'typeText', 'payClosed', 'resource'];

    public function getStatusTextAttribute(): string
    {
        if (empty($this->getAttributes()['statusText'])) return "";
        return !empty(ORDER_STATUS[$this->getAttributes()['statusText']]) ? ORDER_STATUS[$this->getAttributes()['statusText']] : '未知状态';
    }

    public function getTypeTextAttribute(): string
    {
        if (empty($this->getAttributes()['typeText'])) return "";
        if ($this->type != 3 && $this->type != 4)
            return !empty(ORDER_TYPE[$this->getAttributes()['typeText']]) ? ORDER_TYPE[$this->getAttributes()['typeText']] . ($this->getAttribute('type') == 1 ? ' [' . $this->getAttributes()['courseName'] . ']' : ' [' . $this->getAttributes()['cdkeyCode'] . ']') : '';
        else
            return !empty(ORDER_TYPE[$this->getAttributes()['typeText']]) ? ORDER_TYPE[$this->getAttributes()['typeText']] : '';
    }

    public function getPayClosedAttribute(): bool
    {
        if (is_null($this->buyAt)) return true;
        if (Carbon::now()->diffInHours(Carbon::make($this->buyAt)) > 1) return true;
        else return false;
    }

    public function getResourceAttribute()
    {
        switch ($this->type) {
            case 1:
                return Qh_Course::find($this->courseId);
            case 2:
                return Cdkey::find($this->relationId);
            case 3:
                return LearnVideo::find($this->relationId);
            case 4:
                return CourseColumn::find($this->relationId);
            default:
                return null;
        }
    }
}
